<template>
  <div class="container">
    <!-- 导航栏 -->
    <van-nav-bar :title="route.query.type === 'edit' ? '编辑地址' : '新增地址'" left-arrow
      @click-left="router.push({ path: '/address', query: { title: '地址管理' } })" />
    <!-- 编辑地址的区域 -->
    <van-address-edit :area-list="areaList" show-postal show-delete show-set-default show-search-result
      :search-result="searchResult" :area-columns-placeholder="['请选择', '请选择', '请选择']" :address-info="AddressInfo"
      @save="onSave" @delete="onDelete" @change-detail="onChangeDetail" />
  </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router"
import { ref, onMounted } from "vue";
import { areaList } from "@vant/area-data";
import { showConfirmDialog } from "vant";

const router = useRouter()
const route = useRoute()

let searchResult = ref([])
let AddressInfo = ref(JSON.parse(route.query.data ? route.query.data : "{}"));

function onSave(content) {
  console.log(content);
  let data = {
    content, // 修改后的数据
    type: route.query.type, // 业务类型
  };
  // 添加新地址
  //userInfoStore.addAddress(userInfoStore, data);
  let newAddress = data.content
  let userInfo = JSON.parse(sessionStorage.getItem("userInfo"))
  // 对业务类型进行判断
  if (data.type != "edit") {
    // 新增操作
    // 判断添加的数据是否有id，如果没有则根据列表长度计算
    if (!newAddress.id) {
      newAddress.id = userInfo.addressList.length + 1
    }
    userInfo.addressList.push(newAddress)
  } else {
    // 更新
    const index = userInfo.addressList.findIndex(item => item.id == newAddress.id)
    userInfo.addressList.splice(index, 1, newAddress)
  }
  sessionStorage.setItem("userInfo", JSON.stringify(userInfo))
  // 返回地址列表页面
  router.push({ path: "/address", query: { title: "地址管理" } });
}
// 删除事件
function onDelete(content) {
  // 对业务类型进行判断
  if (route.query.type == "edit") {
    // 进行弹窗提醒
    showConfirmDialog({
      title: "警告",
      message: "是否删除“" + content.name + "”这个地址？",
    })
      .then(() => {
        // on confirm
        // 删除地址
        let userInfo = JSON.parse(sessionStorage.getItem("userInfo"))
        const index = userInfo.addressList.findIndex(item => item.id == content.id)
        userInfo.addressList.splice(index, 1)
        sessionStorage.setItem("userInfo", JSON.stringify(userInfo))
        // 返回地址列表页面
        router.push({ path: "/address", query: { title: "地址管理" } });
      })
      .catch((err) => {
        // on cancel
        console.log(err)
        console.log("取消删除");
      });
  }
  
}

</script>

<style lang="scss" scoped>
.container {

  :deep .van-nav-bar__arrow,
  :deep .van-nav-bar__title {
    color: #00682f;
  }

  :deep .van-button--danger {
    background-color: #00682f;
    border: #00682f;
  }

  :deep .van-switch--on {
    background-color: #00682f;
  }
}
</style>
